package com.yfree.utils

import java.security.MessageDigest
import java.util.*
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

object YAESCrypt {
    fun encrypt(plainText: String, pwd: String): String {
        return try {
            val digest = MessageDigest.getInstance("SHA-256")
            digest.update(pwd.toByteArray(charset("UTF-8")))
            val keyBytes = ByteArray(32)
            System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.size)
            val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
            cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(keyBytes, "AES"), IvParameterSpec(byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))
            String(Base64.getEncoder().encode(cipher.doFinal(plainText.toByteArray(charset("UTF-8"))))).replace(System.getProperty("line.separator").toRegex(), "")
        } catch (e: Exception) {
            ""
        }
    }

    fun decrypt(cryptedText: String?, pwd: String): String {
        return try {
            val digest = MessageDigest.getInstance("SHA-256")
            digest.update(pwd.toByteArray(charset("UTF-8")))
            val keyBytes = ByteArray(32)
            System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.size)
            val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
            cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(keyBytes, "AES"), IvParameterSpec(byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))
            String(cipher.doFinal(Base64.getDecoder().decode(cryptedText)))
        } catch (e: Exception) {
            ""
        }
    }
}
